//2018-0516重构，新增值列表项，编辑值列表项，包括自定义与系统值列表项
//2018-10-09重构，这是侧滑页编辑与新增，只保留系统值列表，自定义值列表跳转页面
import React from 'react';
import {connect} from 'react-redux';
import {deepCopy, messages} from 'share/common';
import {Form, Input, Switch, Button, Icon, message} from 'antd';
import {LanguageInput} from 'components/index';
import valueListService from 'containers/setting/value-list/value-list.service';
import 'styles/setting/value-list/new-value.scss';
//默认的值列表项
const defaultVauleItem = {
  code: "",
  value: "",
  messageKey: "",
  i18n: {},
  enabled: true
}
const FormItem = Form.Item;
class ValueList extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      loading: false,
      id: null,
      //编辑时的信息
      record: defaultVauleItem,
      customEnumerationItemOID: "",
      systemInit: null,  //是否为系统初始化的值
    };
  }
  componentWillReceiveProps(nextProps) {
    if (nextProps.params.record && !nextProps.params.hasInit) {
      //编辑
      //这个地方不能用传入的数据，需要请求后端的，因为有多语言对象
      this.getValue(nextProps.params.record.customEnumerationItemOID);
      nextProps.params.hasInit = true;
      this.setState({
        systemInit: nextProps.params.systemInit
      })
    } else if (!nextProps.params.record && !nextProps.params.hasInit) { //新建
      nextProps.params.hasInit = true;
      this.setState({
        record: deepCopy(defaultVauleItem),
        customEnumerationItemOID: "",
        data: [],
        systemInit: nextProps.params.systemInit
      }, () => {
        this.props.form.resetFields()
      })
    }
  }

  getValue(customEnumerationItemOID) {
    valueListService.getValue(customEnumerationItemOID)
      .then((res) => {
        let data = res.data;
        if (data.i18n) {
        } else {
          data.i18n = {}
        }
        this.setState({
          record: data,
          customEnumerationItemOID: customEnumerationItemOID,
        }, () => {
          this.props.form.resetFields();
        })
      })
  }

  validateMessageKeyLengthErr = (messageKey) => {
    if (messageKey === null || messageKey === undefined || messageKey === "") {
      // 请填写名称
      message.warn(messages('setting.key336'/*请填写名称*/));
      return true;
    }
    if (messageKey && messageKey.length && messageKey.length > 300) {
      //需求 4759 长度修改为300
      message.warn(messages('setting.key1794')/*名称最多输入300个字符*/);
      return true;
    }
  }

  handleSave = (e) => {
    e.preventDefault();
    if (this.validateMessageKeyLengthErr(this.state.record.messageKey)) {
      return
    }
    this.props.form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        const {customEnumerationItemOID} = this.state;
        values.customEnumerationOID = this.props.params.customEnumerationOID;
        //多语言
        values.i18n = this.state.record.i18n;
        values.messageKey = this.state.record.messageKey;
        if (customEnumerationItemOID) { //更新
          values.customEnumerationItemOID = customEnumerationItemOID;
          values.id = this.state.id || this.state.record.id;
        }
        if(customEnumerationItemOID){
          this.updateValue(values)
        }else {
          this.newValue(values)
        }
      }
    })
  };
  //新增
  newValue(value){
    this.setState({loading: true});
    valueListService.newValue(value)
      .then(res => {
        if (res.status === 200) {
          message.success(messages('common.save.success', {name: ''}));
          this.setState({loading: false});
          this.props.close(true)
        }
      })
      .catch(e => {
        this.setState({loading: false});
      })
  }
  //更新
  updateValue(value){
    this.setState({loading: true});
    valueListService.updateValue(value)
      .then(res => {
        if (res.status === 200) {
          message.success(messages('common.save.success', {name: ''}));
          this.setState({loading: false});
          this.props.close(true)
        }
      })
      .catch(e => {
        this.setState({loading: false});
      })
  }

  onCancel = () => {
    this.props.close();
  };
//名称：自定义值列表项多语言
  i18nNameChange = (name, i18nName) => {
    this.state.record.messageKey = name;
    if (!this.state.record.i18n) {
      this.state.record.i18n = {};
    }
    this.state.record.i18n.messageKey = i18nName;
  }

  render() {
    const {getFieldDecorator} = this.props.form;
    const {loading, record, systemInit} = this.state;
    const formItemLayout = {
      labelCol: {span: 6},
      wrapperCol: {span: 14, offset: 1},
    };
    return (
      <div className="new-value">
        <Form onSubmit={this.handleSave}>
          <div className="common-item-title">{messages('setting.key1240'/*基本信息*/)}</div>

          <FormItem {...formItemLayout} label={messages('setting.key1225'/*值名称*/)}>
            {getFieldDecorator('messageKey', {
              rules: [{
                required: true,
                message: messages('common.please.enter'),
              }],
              initialValue: record ? record.messageKey : ''
            })(
              <div>
                <LanguageInput
                  disabled={systemInit}
                  name={record ? record.messageKey : ""}
                  i18nName={record && record.i18n && record.i18n.messageKey ? record.i18n.messageKey : null}
                  isEdit={record && record.id}
                  nameChange={this.i18nNameChange}
                />
              </div>
            )}
          </FormItem>

          <FormItem {...formItemLayout} label={messages('setting.key1224'/*编码*/)}>
            {getFieldDecorator('value', {
              rules: [{
                required: true,
                message: messages('common.please.enter'),
              }, {
                max: 100,
                message: messages('setting.key343'/*最多输入100个字符*/),
              },
              ],
              initialValue: record ? record.value : ''
            })(
              <Input placeholder={messages('common.please.enter')}
                     disabled={systemInit || record.id}/>
            )}
          </FormItem>


          <FormItem {...formItemLayout} label={messages('setting.key767')/*序号*/}>
            {getFieldDecorator('sequenceNumber', {
              initialValue: record ? record.sequenceNumber : '',
              rules: [
                {
                  message: messages('setting.key1448'/*请输入正整数*/),
                  validator: (rule, value, cb) => {
                    if (value === null || value === undefined || value === "") {
                      cb();
                      return;
                    }
                    //去掉空格
                    value = value.replace(/ /g, '');
                    if (value.split(".").length > 1) {
                      cb(false);
                    } else {
                      cb();
                    }
                  },
                },
              ]
            })(
              <Input placeholder={messages('common.please.enter')}/>
            )}
            <div className="form-index-tips"> {messages('setting.key1663')/*按照序号由小到大排序，不填默认为999。序号之间尽量保持一定的步长，便于后续调整，如首位10，间隔10。*/}
            </div>
          </FormItem>
          <FormItem {...formItemLayout} label={messages('common.remark')}>
            {getFieldDecorator('remark', {
              rules: [{
                max: 200,
                message: messages('setting.key1226'/*最多输入200个字符*/),
              }],
              initialValue: record ? record.remark : ''
            })(
              <Input placeholder={messages('setting.key1226'/*最多输入200个字符*/)}/>
            )}
          </FormItem>
          <FormItem {...formItemLayout} label={messages('common.column.status')}>
            {getFieldDecorator('enabled', {
              valuePropName: 'checked',
              initialValue: record ? record.enabled : true
            })(
              <Switch checkedChildren={<Icon type="check"/>}
                      unCheckedChildren={<Icon type="cross"/>}/>
            )}
          </FormItem>
          <div className="slide-footer">
            <Button type="primary" htmlType="submit" loading={loading}>{messages('common.save')}</Button>
            <Button onClick={this.onCancel}>{messages('common.cancel')}</Button>
          </div>
        </Form>
      </div>
    )
  }
}

function mapStateToProps(state) {
  return {}
}

const WrappedValueList = Form.create()(ValueList);

export default connect(mapStateToProps)(WrappedValueList);

